'use strict';

const Controller = require('egg').Controller;

class JwtController extends Controller {

  async doLogin() {
    const ctx = this.ctx;
    const user = ctx.request.body.user;
    const { username, password } = user;
    // 询问是否有该用户
    const result = await ctx.model.User.findAll({ where: { username, password } });
    if (result.length) { // 如果有该用户生成token
      const token = this.app.jwt.sign(user, this.app.config.jwt.secret);
      this.ctx.body = {
        code: 200,
        token,
        user_info: result[0],
      };
    } else {
      this.ctx.body = {
        code: '400',
        msg: '用户名或密码错误',
      };
    }
  }

  async doRegister() {
    const ctx = this.ctx;
    const user = ctx.request.body.user;
    const { username, password } = user;
    // 询问是否有该用户
    const result = await ctx.model.User.findAll({ where: { username } });
    if (result.length) { // 如果有该用户则通知用户已有该用户
      this.ctx.body = {
        code: '400',
        msg: '用户名已存在',
      };
    } else {
      try {
        await ctx.model.User.create({ username, password });
        this.ctx.body = {
          code: 200,
          msg: '注册成功',
        };
      } catch (e) {
        this.ctx.body = {
          code: 500,
          msg: '服务器出错',
        };
      }
    }
  }

  async getUserInfo() {
    const ctx = this.ctx;
    const token = ctx.request.header.token;
    const decode = ctx.app.jwt.verify(token, ctx.app.config.jwt.secret);
    const result = await ctx.model.User.findAll({ where: { username: decode.username } });

    if (result.length) {
      this.ctx.body = {
        code: 200,
        user_info: result[0],
      };
    } else {
      this.ctx.body = {
        code: '403',
        msg: 'token 验证不通过',
      };
    }

  }
}

module.exports = JwtController;
